package com.hu.boot.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

// 给 Controller 控制器添加统一的操作或处理
@ControllerAdvice
public class GlobalExceptionHandler {

    // @ExceptionHandler 用于处理指定的异常, value 属性用于指定处理异常的类型
    // 用于捕获 Controller 中抛出的指定类型的异常,从而达到不同类型的异常区别处理的目的
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<String> exceptionHandler(Exception ex) {
        System.out.println("进入全局异常处理");
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = UserNameNotFoundException.class)
    @ResponseBody
    public ResponseEntity<String> userNameNotFoundExceptionHandler(Exception ex) {
        System.out.println("进入全局自定义异常处理");
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
